package com.flower.tokenCenter.service;

import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.flower.tokenCenter.config.AppConfig;
import com.flower.tokenCenter.entity.TokenEntity;
import com.flower.tokenCenter.utils.HttpUtil;
import com.flower.tokenCenter.utils.MD5Util;

@Service
public class TokenService {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Value("#{'${wechat.official.appid}'.split(',')}")
	private List<String> appid;

	@Value("#{'${wechat.official.secret}'.split(',')}")
	private List<String> secret;
	
	public void syncOfficialToken() {
		if(appid.size() == secret.size()) {
			logger.info(df.format(new Date())+"-token开始刷新");
			for(int i =0;i< appid.size();i++) {
				this.getTokenFromWeChat(appid.get(i), secret.get(i));
			}
			logger.info(df.format(new Date())+"-token结束刷新");
		}else {
			logger.error("错误的公众号配置");
		}
	}
	
	
	/**  
	
	 * <p>Title: getTokenFromWeChat</p>  
	
	 * <p>Description:申请token 并放入map中 </p>  
	
	 * @return  
	
	 */  
	public void getTokenFromWeChat(String appid,String secret) {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret+"";
	    JSONObject params = new JSONObject();
	    JSONObject doPost = HttpUtil.doPost(url, params);
	    String access_token = (String) doPost.get("access_token");
		if(null != access_token) {
			AppConfig.officialToken.put(appid, new TokenEntity(access_token, new Date()));
		}else {
			logger.error("公众号:"+appid+"token获取失败");
		}
		
	}


	/**  
	
	 * <p>Title: getToken</p>  
	
	 * <p>Description: 从map中获取token</p>  
	
	 * @param appId2
	 * @param nonceStr
	 * @param sign
	 * @return  
	
	 */  
	public TokenEntity getToken(String appId, String nonceStr, String sign) {
		String md5Encode = MD5Util.md5Encode(appId+nonceStr);
		if(sign.equalsIgnoreCase(MD5Util.md5Encode(md5Encode+appId))) {
			//简易验证通过
			TokenEntity tokenEntity = AppConfig.officialToken.get(appId);
			if(tokenEntity != null) {
				return tokenEntity;
			}
			return null;
			
		}
		return null;
	}


	/**  
	
	 * <p>Title: refreshToken</p>  
	
	 * <p>Description:刷新token </p>  
	
	 * @param appId
	 * @param nonceStr
	 * @param sign  
	
	 */  
	public TokenEntity refreshToken(String appId, String nonceStr, String sign) {
		String md5Encode = MD5Util.md5Encode(appId+nonceStr);
		if(sign.equalsIgnoreCase(MD5Util.md5Encode(md5Encode+appId))) {
			//简易验证通过
			int index = appid.indexOf(appId);
			this.getTokenFromWeChat(appId, secret.get(index));
			TokenEntity tokenEntity = AppConfig.officialToken.get(appId);
			if(tokenEntity != null) {
				return tokenEntity;
			}
			return null;
			
			
		}
		return null;
		
	}


	public void deleteToken(String appId, String nonceStr, String sign) {
		String md5Encode = MD5Util.md5Encode(appId+nonceStr);
		if(sign.equalsIgnoreCase(MD5Util.md5Encode(md5Encode+appId))) {
			//简易验证通过
			AppConfig.officialToken.remove(appId);
		}
		
	}
	
	

}
